package com.earthea.message.controller;

import com.earthea.application.domain.LoginUser;
import com.earthea.application.user.common.entity.BaseRsp;
import com.earthea.application.user.common.util.SecurityUtils;
import com.earthea.message.entity.domain.Message;
import com.earthea.message.entity.request.PublishMessageReq;
import com.earthea.message.entity.response.MessageRsp;
import com.earthea.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @GetMapping
    public MessageRsp list() {
        List<Message> messages = messageService.selectAll();
        MessageRsp response = BaseRsp.success(MessageRsp.class);
        response.setMessages(messages);
        return response;
    }

    @PostMapping
    public BaseRsp publish(@RequestBody PublishMessageReq publishMessageReq) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Message message = new Message();
        message.setUserId(loginUser.getUserId());
        message.setParentId(publishMessageReq.getParentId());
        message.setContent(publishMessageReq.getContent());
        return messageService.insert(message) > 0 ? BaseRsp.success() : BaseRsp.failed();
    }
}
